<script setup lang="ts">
import { onMounted } from "vue";
import { createThumbnail } from "./thumbnail.ts";

onMounted(() => {
  const videoInput = document.getElementById("videoInput");
  const thumbnailContainer = document.getElementById("thumbnailContainer");
  const canvas = document.getElementById("canvas") as HTMLCanvasElement;
  videoInput?.addEventListener("change", async (event: any) => {
    const file = event?.target?.files?.[0];

    if (file) {
      // const videoUrl = URL.createObjectURL(file);

      // // 使用FFmpeg.wasm处理视频
      // const thumbnailImage = await createThumbnail(videoUrl);

      // URL.revokeObjectURL(videoUrl);

      // // 显示封面图
      // thumbnailContainer!.innerHTML = "";
      // thumbnailContainer!.appendChild(thumbnailImage);

      // fangshi2

      const video = document.createElement("video");
      video.src = URL.createObjectURL(file);

      video.addEventListener("loadedmetadata", () => {
        if (!canvas) return;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        const ctx = canvas.getContext("2d")!;
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        const imageData = ctx.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        ).data;

        const isBlack = imageData.every((value) => value === 0);

        if (!isBlack) {
          thumbnailContainer!.innerHTML = "";
          thumbnailContainer!.appendChild(canvas.toDataURL("image/jpeg"));
        }

        // 释放视频资源
        URL.revokeObjectURL(video.src);
      });
    }
  });
});
</script>

<template>
  <input type="file" accept="video/*" id="videoInput" />
  <div id="thumbnailContainer"></div>
  <canvas id="canvas" style="display: none"></canvas>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
